/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief This is an example for using the MaCICtrl interface.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: MaCICtrlClientExample.cpp,v 1.4 2009-05-13 07:18:15 amaula Exp $
 *
 */
#include "MaCICtrlClient.hpp"

//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************

//*****************************************************************************
enum EMode { KModeDebug = 0, KModeSLScan = 1 };
//*****************************************************************************
static int verbose = 1;
static int mode = KModeSLScan;
static unsigned char authkey[16] = "r6oZE93Ba1Q6KKn";

//*****************************************************************************
using namespace MaCI::MaCICtrl;
//*****************************************************************************

void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tMaCICtrlClientExample [OPTIONS] <TargetGIMnetName>\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";
  std::string nukeTarget = "";

  // Objects
  //  bool run = true;
  gimi::GIMI g;
  MaCI::MaCICtrl::CMaCICtrlClient mcc(&g, -1);

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(1);
  debugSetLogFilename("MaCICtrlClientExample.log");

  // Greet
  fprintf(stderr,
	  "\nMaCICtrlClientExample - MaCICtrl Client Interface Example - $Revision: 1.4 $\n\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "u:p:hqv");
    switch(c) {
    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      if (argc > optind) {
	nukeTarget = argv[optind];
      }
      parse = false;
      break;
    }
  }

  /*
  ///////////////  // JUST TESTING
  SMaCISL msl;
  msl.FromMaCISL("Foo.bar.zaa.zoo.zii.MaCI_Alarm.MunInstance");
  dPrint(ODTEST, "Group: '%s'", msl.group.c_str());
  dPrint(ODTEST, "Interface: '%s'", msl.interface.c_str());
  dPrint(ODTEST, "Instance: '%s'", msl.instance.c_str());
  exit(666);
  /////////////////////
  */
  MaCI::EMaCIError e;
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    ownSleep_ms(500);

    // Attempt to Open Client
    if ( (e = mcc.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open MaCICtrlClient instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {
      // NUKE
      if (nukeTarget.size()) {
	CMaCICtrlData req;
	req.CreateInternalBinBag();
	req.SetCommand(KCommandKill);
	const bool r = g.send(nukeTarget,
			      req.GetBinBagContainerPtr()->GetBuffer(),
			      req.GetBinBagContainerPtr()->GetBufferSize(),
			      GIMI_PROTOCOL_MACI_MACICTRL,
			      0,
			      0) == GIMI_OK;                       
      }


    }
  }
  
  dPrint(1,"MaCICtrlClientExample completed.");
  
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

